const Koa = require('koa');

// 注意require('koa-router')返回的是函数:
const router = require('koa-router')();

const app = new Koa();
const chalk = require('chalk')

const article = []
// log request URL:
app.use(async (ctx, next) => {
    console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
    await next();
});

// add url-route:
router.get('/hello/:name', async (ctx, next) => {
    var name = ctx.params.name;   //name是一个变量，通过ctx.params.name访问
    ctx.response.body = `<h1>Hello, ${name}!</h1>`;
});

router.post('/a', async (ctx, next) => {
    // var name = ctx.params.name;   //name是一个变量，通过ctx.params.name访问
    let postdata = "";
      ctx.req.addListener('data', (data) => {
        postdata += data
      })
      ctx.req.addListener("end",function(){
        // let parseData = parseQueryStr(postdata)
        // resolve( parseData )
        chalk.green('1122',JSON.parse(postdata).params['pageNo'])
      })
    ctx.response.body = `11111`;
});

router.post('/storage/article', async (ctx, next) => {
    let postdata = "";
    ctx.req.addListener('data', (data) => {
        postdata += data
    })
    ctx.req.addListener("end",function(){
    // let parseData = parseQueryStr(postdata)
    // resolve( parseData )
        article.push(JSON.parse(postdata).params)
    })
    ctx.response.body = `2222`;
});

router.get('/getAll/article', async (ctx, next) => {
    const rep = JSON.stringify(article)
    chalk.red('hello world')
    ctx.response.body = rep;
});

router.get('/a', async (ctx, next) => {
    let res = {
        "title":"诗云博客测试接口",
        "content": "测试诗云博客接口能否使用"
    }
    const  tempRes = []
    let a = 20
    while(a) {
        tempRes.push(res)
        a--
    }
    const data = {
        'data': tempRes
    }
    ctx.response.body = data;
});

// add router middleware:
app.use(router.routes());

app.listen(3000);
console.log('app started at port 3000...');